package com.boctech.yxt.authcenter.utils;

import com.boctech.yxt.authcenter.entity.JwtProperties;
import com.boctech.yxt.persistance.entity.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {


    private JwtProperties jwtProperties;

    public JwtTokenUtils(JwtProperties jwtProperties){
        this.jwtProperties = jwtProperties;
    }


    public String generateToken(SysUser user){
        HashMap<String, Object> map = new HashMap<>();
        map.put("sub", user.getUsername());
        map.put("created", System.currentTimeMillis());
        return generateToken(map);
    }

    public String generateToken(Map<String, Object> claims){
        Date date = new Date(System.currentTimeMillis() + jwtProperties.getExpiration());
        return Jwts.builder().setClaims(claims)
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret()).compact();
    }

    public Boolean validateToken(String token, String username) {
        String nameFromToken = getUserNameFromToken(token);
        return nameFromToken != null && nameFromToken.equals(username) && (! isTokenExpired(token));
    }

    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    public String getUserNameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }


    /**
     * 从令牌中获取数据声明,如果看不懂就看谁调用它
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }



}
